<script setup>
import { getNewsList } from '@/api/news';
import { onMounted, ref } from 'vue';
import { onBeforeRouteUpdate, useRouter, useRoute } from 'vue-router';

const router = useRouter();
const route = useRoute();

// 初始化 page 和 size
const ini = ref({
    total: 1,
    page: parseInt(route.query.page) || 1,
    size: 9
});

// 获取新闻列表
const newsList = ref([]);
const getList = async () => {
    const res = await getNewsList({ page: ini.value.page, size: ini.value.size });
    newsList.value = res.data.data.news;
    ini.value.total = res.data.data.total;
};

// 初始加载新闻列表
onMounted(() => { getList() })

const change = (val) => {
    ini.value.page = val;
    router.push({
        path: "/news",
        query: {
            page: val,
            size: ini.value.size
        }
    });
    window.scrollTo({ top: 0 })
};

onBeforeRouteUpdate((to) => {
    console.log('组件内的守卫:beforeRouteUpdate:', to.query);
    ini.value.page = parseInt(to.query.page) || 1;
    getList();
});

</script>

<template>
    <div class="newlist">
        <div class="newslist-main">
            <div class="newslist-main_items" v-for="item in newsList" :key="item._id">
                <router-link :to="`detail/${item._id}`">
                    <img :src="item.img" alt="">
                    <p>{{ item.title }}</p>
                    <p>{{ item.createAt }}</p>
                </router-link>
            </div>
        </div>
        <div class="example-pagination-block">
            <div class="example-demonstration"></div>
            <el-pagination layout="prev, pager, next" :total="ini.total" :page-size="ini.size"
                @current-change="change" />
        </div>
    </div>
</template>

<style lang="scss" scoped>
.newlist {
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color: #fcfcfc;
    padding-bottom: 60px;
}



.newslist-main {
    width: 1200px;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding-top: 82px;


    .newslist-main_items {
        display: flex;
        flex-direction: column;
        margin-bottom: 60px;
        width: 386px;
        height: 328px;
        background-color: #ffffff;
        box-shadow: 0px 0px 10px 0px rgba(237, 237, 237, 0.7);

        p {
            padding-left: 20px;
            font-size: 14px;
            color: #333;
        }

        p:nth-of-type(1) {
            padding-top: 20px;
            padding-bottom: 30px;
            font-size: 16px;
        }
    }
}
</style>